<template>
  <grid-layout :layout.sync="childGadgets"
               :col-num="12"
               :row-height="10"
               :is-draggable="dashbordDefaultSetting.allowDragging"
               :is-resizable="dashbordDefaultSetting.allowResizing"
               :vertical-compact="true"
               :use-css-transforms="true">
    <template v-if="Array.isArray(childGadgets)&&childGadgets.length>0">
      <grid-item v-for="(item,index) in childGadgets"
                 class="grid-item-css"
                 :x="item.x"
                 :y="item.y"
                 :w="item.w"
                 :h="item.h"
                 :i="item.i"
                 :key="item.i"
                 :static="item.static"
                 @container-resized="containerResizedEvent"
                 @resized="resizedEvent"
                 @mouseenter.native="mouseEnterModule(index)"
                 @mouseleave.native="mouseLeaveModule(index)">
        <div class="widget_div" style="width:100;height:100%">
          <div v-if="editMode&&item&&item.showSetting&&item.showSetting === 'show'"
             style="height:20px;lineHeight:20px;position:absolute;top:2px;right:2px;z-index:2020;background:#ffffff;">
          &nbsp;
          <i @mouseenter="moveComponent(true)"
             @mouseleave="moveComponent(false)"
             :title="$t('custom.move')"
             class="el-icon-rank"
             v-if="!(item.com==='pageheadergadget')"
             style="cursor:pointer;"></i>&nbsp;
          <i v-if="$hasPermission('sys:tenant:model:allowtomanage:report:temmodel')"
             @click="editComponent(item.i)"
             :title="$t('custom.edit')"
             class="el-icon-s-operation"
             style="cursor:pointer;"></i>&nbsp;
          <i @click="closeComponent(item.i)"
             :title="$t('custom.remove')"
             v-if="!(item.com==='pageheadergadget')"
             class="el-icon-close"
             style="cursor:pointer;"></i>&nbsp;
        </div>
        <component :editMode='editMode'
                   style="width:100;height:calc(100% - 32px)"
                   :gadgetInfo='item'
                   @dragChanged='gadgetDragChanged'
                   :ref="`gadgets_${tabsIndex}`"
                   @removed='gadgetRemoved'
                   :id='item.i'
                   :pageId='pageId'
                   :businessType='businessTypeForWidget'
                   :reportNameForPage='reportNameForPage'
                   :is="item.com"></component>
        </div>
      </grid-item>
    </template>
  </grid-layout>
</template>

<script>
import VueGridLayout from 'vue-grid-layout'

import pvtable from '@/components/gadget/pvtable/pvtable-gadget.vue'
import grid from '@/components/gadget/grid/grid-gadget.vue'
import checklistgadget from '@/components/gadget/check-list/checklist-gadget.vue'
import gridgadget from '@/components/gadget/grid-gadget/grid-gadget.vue'
import hierarchygridgadget from '@/components/gadget/hierarchy-grid/hierarchygrid-gadget.vue'
import crudformgadget from '@/components/gadget/crud-form/crudform-gadget.vue'
import chartgadget from '@/components/gadget/chart-line/line-gadget.vue'
import barchartgadget from '@/components/gadget/chart-bar/bar-gadget.vue'
import piechartgadget from '@/components/gadget/chart-pie/pie-gadget.vue'
import listmenu from '@/components/gadget/list-menu/list-menu-gadget.vue'
import dateRangeSlicer from '@/components/gadget/dateRange-slicer/daterange-gadget.vue'
import dateSlicer from '@/components/gadget/date-slicer/date-slicer-gadget.vue'
import runReport from '@/components/gadget/runreport-action/runreport-gadget.vue'
import kpigadget from '@/components/gadget/kpi/kpi-gadget.vue'
import circulargauge from '@/components/gadget/circular-gauge/circular-gadget.vue'
import cardicon from '@/components/gadget/card-icon/card-icon-gadget.vue'
import cardlinegadget from '@/components/gadget/card-line/card-line-gadget.vue'
import autorefreshgadget from '@/components/gadget/auto-refresh/auto-refresh-gadget.vue'
import dropdownlistgadget from '@/components/gadget/dropdown-list-slicer/dropdown-list-gadget.vue'
import menulistgadget from '@/components/gadget/customized/menuList/menuList-gadget.vue'
import linkbuttongadget from '@/components/gadget/link-button/link-button-gadget.vue'
import checkboxgadget from '@/components/gadget/checkbox-slicer/checkbox-gadget.vue'
import multiselectgadget from '@/components/gadget/multi-select-slicer/multi-select-gadget'
import cardnumbergadget from '@/components/gadget/card-number/card-number-gadget.vue'
import htmleditorgadget from '@/components/gadget/html-editor/html-editor-gadget.vue'
// import treemapgadget from '@/components/gadget/tree-map/tree-map-gadget.vue'
import drilldowntreemapgadget from '@/components/gadget/drilldown-treemap/drilldown-treemap-gadget.vue'
import placeholdergadget from '@/components/gadget/place-holder/place-holder-gadget.vue'
import processgaugegadget from '@/components/gadget/gauge-stage/gauge-stage-gadget.vue'
import scorecardgadget from '@/components/gadget/score-card-gadget/score-card-gadget.vue'
import cardlablegadget from '@/components/gadget/card-lable/card-lable-gadget.vue'
import kanbangadget from '@/components/gadget/kanban/kanban-gadget'
import pageheadergadget from '@/components/gadget/page-header/page-header-gadget.vue'
import deptdefaultslicergadget from '@/components/gadget/customized/dept-default-slicer/dept-default-slicer-gadget.vue'
import nextticketviewgadget from '@/components/gadget/next-ticket-view/next-ticket-view-gadget'
// Customized
import bottriggerreportgadget from '@/components/gadget/customized/bot-trigger/bot-trigger-gadget.vue'
import bottriggerpvtablegadget from '@/components/gadget/customized/bot-trigger/bot-trigger-pvtble-gadget.vue'
import bottriggeruserreportgadget from '@/components/gadget/customized/bot-trigger-user/bot-trigger-user-gadget.vue'
import crudgadget from '@/components/gadget/crud-gadget/crud-gadget.vue'
import stepgadget from '@/components/gadget/step-line/step-line-gadget.vue'
import newstepgadget from '@/components/gadget/new-step-line/new-step-line-gadget.vue'
import homepagegadget from '@/components/gadget/home-page/home-page-gadget.vue'
import customizedmultiselectgadget from '@/components/gadget/customized/multi-select-slicer/multi-select-gadget'
import customizeduserdropdownlistgadget from '@/components/gadget/customized/user-dropdown-list-slicer/user-dropdown-list-gadget.vue'
import customizedusermultipledropdownlistgadget from '@/components/gadget/customized/user-multiple-dropdown-list-slicer/user-multiple-dropdown-list-gadget.vue'
import appstabsgadget from '@/components/gadget/apps-tabs/apps-tabs-gadget.vue'
import customizedbotdetailinfogadget from '@/components/gadget/customized/bot-detail-info/bot-detail-info-gadget.vue'
import customizedbotdesigngadget from '@/components/gadget/customized/bot-design/index.vue'
import customizedbotdetailrunhistorygadget from '@/components/gadget/customized/bot-detail-run-history/bot-detail-run-history-gadget.vue'
import attendancegadget from '@/components/gadget/customized/attendance-gadget/attendance-gadget.vue'
import recordgadget from '@/components/gadget/customized/record-gadget/record-gadget.vue'
import usergadget from '@/components/gadget/customized/user-gadget/user-gadget.vue'
import botsgadget from '@/components/gadget/customized/bots-gadget/bots-gadget.vue'
import workschedulegadget from '@/components/gadget/customized/workschedule-gadget/workschedule-gadget.vue'
import treegridgadget from '@/components/gadget/tree-grid-gadget/tree-grid-gadget.vue'
import apigridgadget from '@/components/gadget/api-grid-gadget/api-grid-gadget.vue'
import {
  dashboardGadgetList, slicerGadgetTypeList
} from '@/utils/data-json'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import enterinputgadget from '@/components/gadget/enter-input-slicer/enter-input-gadget.vue'
import crudformplusgadget from '@/components/gadget/crud-form-plus/crudform-plus-gadget.vue'
import { union } from "lodash"
export default {
  mixins: [mixinGadgetViewModule],
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    grid,
    checklistgadget,
    gridgadget,
    hierarchygridgadget,
    crudformgadget,
    htmleditorgadget,
    pvtable,
    chartgadget,
    barchartgadget,
    piechartgadget,
    listmenu,
    dateRangeSlicer,
    runReport,
    kpigadget,
    circulargauge,
    cardicon,
    cardlinegadget,
    dateSlicer,
    autorefreshgadget,
    dropdownlistgadget,
    treegridgadget,
    menulistgadget,
    linkbuttongadget,
    checkboxgadget,
    multiselectgadget,
    cardnumbergadget,
    // treemapgadget,
    drilldowntreemapgadget,
    placeholdergadget,
    processgaugegadget,
    scorecardgadget,
    cardlablegadget,
    kanbangadget,
    pageheadergadget,
    // Customized
    bottriggerreportgadget,
    bottriggerpvtablegadget,
    bottriggeruserreportgadget,
    crudgadget,
    stepgadget,
    newstepgadget,
    homepagegadget,
    customizedmultiselectgadget,
    customizeduserdropdownlistgadget,
    customizedusermultipledropdownlistgadget,
    deptdefaultslicergadget,
    nextticketviewgadget,
    appstabsgadget,
    customizedbotdetailinfogadget,
    customizedbotdesigngadget,
    customizedbotdetailrunhistorygadget,
    attendancegadget,
    recordgadget,
    usergadget,
    botsgadget,
    workschedulegadget,
    apigridgadget,
    enterinputgadget,
    crudformplusgadget
  },
  props: {
    gadgets: {
      type: Array,
      default: () => []
    },
    editMode: {
      type: Boolean,
      default: false
    },
    tabsIndex: {
      type: String,
      default: 'index_0'
    }
  },
  data () {
    return {
      dashbordDefaultSetting: {
        allowResizing: false,
        allowDragging: false,
        responsive: true
      },
      businessTypeForWidget: 'Custom',
      layoutLists: dashboardGadgetList,
      slicer: {},
      key: 0
    }
  },
  watch: {
    editMode (val) {
      if (val) {
        this.$set(this.dashbordDefaultSetting, 'allowResizing', true)
        this.$set(this.dashbordDefaultSetting, 'allowDragging', true)
        // this.$set(this.dashbordDefaultSetting, 'responsive', true)
      } else {
        this.$set(this.dashbordDefaultSetting, 'allowResizing', false)
        this.$set(this.dashbordDefaultSetting, 'allowDragging', false)
        // this.$set(this.dashbordDefaultSetting, 'responsive', false)
      }
    }

  },
  computed: {
    childGadgets () {
      var slicerList = []
      var widgetList = []
      this.gadgets.forEach(item => {
        if (slicerGadgetTypeList.find(i => i === item.com)) {
          slicerList.push(item)
        } else {
          widgetList.push(item)
        }
      })
      return slicerList.concat(widgetList)
    },
   
    tabsIndexNumber () {
      if (this.tabsIndex) {
        return Number(this.tabsIndex.replace('index_', ''))
      }
    }
  },
  provide () {
    return {
      gadgetMessageBus: this.gadgetMessageBus,
      slicer: this.slicer
    }
  },
  created () {
    this.getQureAll()
  },
  activated () {
    this.getQureAll()
    if (localStorage.getItem('botdetailpageconfig') !== `${this.slicer.pageid}${this.slicer.botId}`) {
      this.publishMessage('runReport')
    }
  },
  methods: {
    resizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      this.updateGadgetsList('update', this.tabsIndexNumber, index, 'h', newH)
      this.updateGadgetsList('update', this.tabsIndexNumber, index, 'w', newW)
      let refsList = this.$refs[`gadgets_${this.tabsIndex}`] || []
      for (let ind = 0; ind < refsList.length; ind++) {
        const elementId = refsList[ind].id
        if (elementId === i && index > -1) {
          this.$refs[`gadgets_${this.tabsIndex}`][ind].resized(i, newH, newW, newHPx, newWPx)
        }
      }
    },
    containerResizedEvent: function (i, newH, newW, newHPx, newWPx) { },
    mouseEnterModule (index) {
      if (this.editMode) {
        this.updateGadgetsList('update', this.tabsIndexNumber, index, 'showSetting', 'show')
      }
    },
    mouseLeaveModule (index) {
      if (this.editMode) {
        this.updateGadgetsList('delete', this.tabsIndexNumber, index, 'showSetting')
      }
    },
    gadgetDragChanged (e) {
      this.dashbordDefaultSetting.allowDragging = e.state
    },
    moveComponent (status) {
      if (this.editMode) {
        this.gadgetDragChanged({
          state: status
        })
      }
    },
    editComponent (componentId) {
      try {
        let index = this.getGadgetIndex(componentId)
        let refsList = this.$refs[`gadgets_${this.tabsIndex}`] || []

        for (let i = 0; i < refsList.length; i++) {
          const elementId = refsList[i].id
          if (elementId === componentId && index > -1) {
            this.$refs[`gadgets_${this.tabsIndex}`][i].showQueryModel()
          }
        }
      } catch (error) { }
    },
    getGadgetIndex (id) {
      return this.childGadgets.findIndex(e => e.i === id)
    },
    closeComponent (componentId) {
      let confirmText = [
        'Are you sure to remove widget from report layout?',
        'Click confirm will continue remove widget and save layout'
      ]
      const newDatas = []
      const h = this.$createElement
      for (const i in confirmText) {
        newDatas.push(h('p', null, confirmText[i]))
      }
      this.$confirm('info', {
        title: this.$t('prompt.title'),
        message: h('div', null, newDatas),
        showCancelButton: true,
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(async () => {
        this.gadgetRemoved({
          id: componentId
        })
      }).catch(_ => { })
    },
    gadgetRemoved (e) {
      var index = this.getGadgetIndex(e.id)
      this.updateGadgetsList('clear', this.tabsIndexNumber, index)
    },
    getQureAll () {
      try {
        let hasQure = window.location.search.split('?').length > 1
        hasQure && window.location.search.split('?')[1].split('&').map(e => {
          this.$set(this.slicer, e.split('=')[0], e.split('=')[1])
        })
      } catch (error) { }
    },
    updateGadgetsList (type, tabIndex, gadgetsIndex, key, value) {
      this.$emit('updateGadgetsList', type, tabIndex, gadgetsIndex, key, value)
    }
  }
}
</script>

<style lang="scss">
.widget_div:hover .more_menu_box {
    display: block;
  }
  .widget_div:hover span.el-icon-more {
    display: block;
  }
</style>
